import { NextRequest, NextResponse } from 'next/server';
import { getDbInstance } from '@/lib/sqlite-database';

export async function GET(request: NextRequest) {
  try {
    const sqliteDb = getDbInstance();
    
    // 确保数据库初始化
    sqliteDb.ensureInitialized();
    
    // 查看devices表结构
    const schema = sqliteDb.get(`PRAGMA table_info(devices)`);
    const allColumns = sqliteDb.all(`PRAGMA table_info(devices)`);
    
    // 尝试查询现有设备
    const existingDevices = sqliteDb.all('SELECT * FROM devices LIMIT 3');
    
    // 测试一个简单的插入操作
    const testDevice = {
      device_id: 'TEST001',
      name: '测试设备',
      classification_name: '测试分类',
      classification_code: 'TEST',
      specialty: '配管专业',
      naming_table_id: '',
      position_table_id: '',
      base_params_table_id: '',
      tech_spec_table_id: '',
      sequence_number: '001',
      remarks: '调试测试'
    };
    
    let testInsertResult = null;
    let testInsertError = null;
    
    try {
      testInsertResult = sqliteDb.insertDevice(testDevice);
    } catch (error) {
      testInsertError = error;
    }
    
    return NextResponse.json({
      tableSchema: allColumns,
      existingDevices,
      testInsertResult,
      testInsertError: testInsertError ? {
        message: testInsertError.message,
        code: testInsertError.code
      } : null
    });
  } catch (error) {
    console.error('调试数据库错误:', error);
    return NextResponse.json({
      error: `调试失败: ${error instanceof Error ? error.message : '未知错误'}`
    }, { status: 500 });
  }
} 